import React, { Component } from 'react';
import {base} from 'nc-lightapp-front';
const {NCIcon,NCFormControl} = base;
import pubUtil from '../../common/pubUtil'
import ObjTypeUtil from '../../utils/ObjTypeUtil'

import AssidModal from '../assidModal';//辅助核算模态框
import './index.less'

export default class AssidModalRedner extends Component {
    constructor(props) {
        super(props);
        this.state = {
            displayName: (props.value || {}).display,
            isQueryShow: false,
            pretentAssData: {}
        };
    }
    componentDidMount(){
        if(this.props.onRef&&ObjTypeUtil.isFunction(this.props.onRef))
            this.props.onRef(this);
        if(!this.props.subjrelationset){//有这个参数就不自动弹框了
            this.iconClick();
        }
        let assidModalRedner=document.getElementById('assidModalRedner');
        let input = assidModalRedner && (assidModalRedner.querySelector('input'));
        if(input&&!this.props.position){
            input.focus();
            this.iconClick();
        }
    }
    handleClose(){
        this.setState({
            isQueryShow: false, 
            pretentAssData: {
                pk_accountingbook:'',
                pk_accasoa:'',
                prepareddate:'',
                pk_org:'',
                assData:[] ,
                assid:'',
                checkboxShow:true,
                checkedAll:true
            }
        });
    }

    iconClick(){
        let pretentAssData = {prepareddate: pubUtil.getSysDateStr(),assData:[],...this.props.getPretentAssData()}
        if(this.props.voucherdate){
            pretentAssData.prepareddate=this.props.voucherdate
        }
        if(pretentAssData.checkboxShow==null){
            pretentAssData.checkboxShow=true;
        }
        pretentAssData.checkedAll=true;
        this.setState({ pretentAssData: pretentAssData })
            window.setTimeout(()=>{
                this.setState({
                    isQueryShow: true });
            },10)
    }
    handleQueryClick(data){
        let display = (this.props.changeDisplay && this.props.changeDisplay(data)) || data.assname;
        if(!display){
            let displayname='';
            data.data.map((one)=>{
                if(one){
                    if(one.pk_Checkvalue){
                        displayname =displayname+ '【'+ one.checktypename + ':'+ (one.checkvaluename?one.checkvaluename:'~')+'】';
                        // continue;
                    }
                }
            })
            display=displayname;
            data.assname=displayname;
        }
        let showname="";
        if(display.length > 10){
            showname=display.substring(0, 10) + '...';
        }else{
            showname= display;
        }
        this.setState({displayName: showname});
        let flag=this.props.doConfirm && this.props.doConfirm(data, display);
        // let flag=true;
        //  window.setTimeout(()=>{
        //     flag=this.props.flag;
        // },1000);
        if(flag){
            if(flag==false){
                this.handleClose();
            }
        }else{
            this.handleClose();
        }
        
    }

    
    clear(){
        this.setState({displayName:'', pretentAssData: {}});
    }
    hotkeyEnter=(event,attrcode,index)=>{
        if(event.key=="Enter"){//enter键
            //hot-key-subjrelation-m_dfreevalueid-1
            let currentEle=event.target;
            let attribute=`hot-key-subjrelation-${attrcode}-${index}`;
            let parentTd = this.findParentTd(currentEle);
            let nextTd = parentTd.nextElementSibling;
            let div = nextTd && (nextTd.querySelector('[tabindex="0"]')|| nextTd.querySelector("input[type='checkbox']"));
            // 如果下一个元素没有找到就继续查找
            if (div === null) {
                this.findNextSiblings({ td: nextTd });
                return;
            }
            // document.body.click();
            div.focus();
            // currentEle.blur();
            this.props.enterEvent();
        }
    }
    findNextSiblings=({ td })=>{
        var nextTd = td.nextElementSibling;
        var currentTr = nextTd && nextTd.parentElement;
        var lastTd = currentTr && findLastTdInRow(currentTr);
        var currentDiv = td.querySelector('[tabindex="0"]');
        var div = nextTd && (nextTd.querySelector('[tabindex="0"]')|| nextTd.querySelector("input[type='checkbox']"));
    
        //如果下个需要聚焦的单元格与最后一个单元相同并且没有可聚焦元素就在下一行查找
        // if ((lastTd === nextTd && div === null) || (lastTd === td && currentDiv === null)) {
        //     findNextRowTd({ tr: currentTr, ViewModel, moduleId, orderOfHotKey });
        //     return;
        // }
    
        if (div === null) {
            findNextSiblings({ td: nextTd});
            return;
        }
        div.focus();
    }
    findParentTd=(el)=>{
        while (el.parentElement) {
            el = el.parentElement;
            if (el.tagName === 'TD') {
                return el;
            }
        }
        return null;
    }
    render() {
        let getClass=(flag)=>{
            if(flag == 'home'){
                if(this.props.position == 'form'){
                    return 'home nc-theme-area-split-bc nc-theme-from-input-bgc';
                }else{
                    return 'home-list nc-theme-area-split-bc nc-theme-from-input-bgc';
                }
            }else if(flag == 'button'){
                if(this.props.position == 'form'){
                    return 'assid-modal-button nc-theme-form-label-c';
                }else{
                    return 'assid-modal-button-list nc-theme-form-label-c';
                }
            }
        }
        let getDisplayName=()=>{
            let formValue=this.props.form&&this.props.form.getAllFormValue('form');
            if((this.props.foolValue || {}).display == ''){
                return '';
            }else{
                let display =this.state.displayName || '';
                if(this.props.foolValue){
                    if(this.props.foolValue.display){
                        display=this.props.foolValue.display;
                    }
                }
                if(formValue&&formValue.rows&&formValue.rows[0]&&formValue.rows[0].values){
                    display=formValue.rows[0].values[this.props.attrcode].display?formValue.rows[0].values[this.props.attrcode].display:'';
                }
                // if((this.state.displayName || '').length > 10){
                if(display.length > 10){
                    return display.substring(0, 10) + '...';
                }else{
                    return display;
                }   
            }
        }
        let getDisplayTitle=()=>{
            if((this.props.foolValue || {}).display == ''){
                return '';
            }else{
                return this.state.displayName;
            }
        }
        return (
            <div id="assidModalRedner">
                <div className={getClass('home')}
                    onKeyDown={(event)=>{
                        this.hotkeyEnter(event,this.props.attrcode,this.props.index);
                    }}
                >
                <NCFormControl
                    // fieldid={item.attrcode}
                    value={getDisplayName()}
                    onChange={(v) => {
                        // let cloneNewLine = deepClone(evidenceColumns);
                        // cloneNewLine.splice(4, 0, number1);
                        // self.setState({
                        // 	evidenceColumns: cloneNewLine
                        // });
                    }}
                />
                <i className="iconfont icon-canzhaozuixin" onClick={this.iconClick.bind(this)} />
                    {/* <table>
                        <tbody>
                            <tr>
                                <td className="assid-modal-title" title={getDisplayTitle()} tabIndex="0"
                                onFocus={
                                    (e)=>{
                                        this.iconClick();
                                    }
                                }
                                >
                                    {getDisplayName()}
                                </td>
                                <td className={getClass('button')}>
                                    <i className="iconfont icon-canzhaozuixin"
                                        onClick={this.iconClick.bind(this)} />
                                    
                                </td>
                            </tr>
                        </tbody>
                    </table> */}
                    <AssidModal
                        isNeedVersion={this.props.isNeedVersion?this.props.isNeedVersion:false}/*是否需要版本参照*/
                        pretentAssData={this.state.pretentAssData}
                        showOrHide = {this.state.isQueryShow}
                        onConfirm = {this.handleQueryClick.bind(this)} 
                        handleClose={this.handleClose.bind(this)}
                    />
                </div>
            </div>
        )
    }
}
